package com.flow.framework.cipher.algorithm;

import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.util.io.IoUtil;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;

/**
 * 算法工具类
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/16
 */
@Slf4j
class AlgorithmUtil {

    /**
     * 获取cipher的doFinal的byte数组
     *
     * @param contentByte contentByte
     * @param cipher      cipher
     * @param maxBlock    maxBlock
     * @return
     */
    static byte[] cipherDoFinal(byte[] contentByte, Cipher cipher, int maxBlock) {
        ByteArrayOutputStream out = null;
        try {
            int inputLen = contentByte.length;
            out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;

            // 对数据分段加解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > maxBlock) {
                    cache = cipher.doFinal(contentByte, offSet, maxBlock);
                } else {
                    cache = cipher.doFinal(contentByte, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * maxBlock;
            }
            return out.toByteArray();
        } catch (Exception e) {
            log.error("decrypt error.", e);
            throw new CheckedException(SystemErrorCode.CIPHER_ERROR, "decrypt error.", e);
        } finally {
            IoUtil.close(out);
        }
    }


}